package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dto.AttrGroupEntityDto;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.vo.AttrGroupEntityVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Resource
    private CategoryServiceImpl categoryService;
    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Autowired
    private AttrDao attrDao;
    @Resource
    private AttrAttrgroupRelationServiceImpl relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        //如果查所有分类 分类id为0
        if (catelogId == 0) {
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    new QueryWrapper<AttrGroupEntity>()
            );
            //设置完整的分类路径
            List<AttrGroupEntity> attrGroupEntityList = setCatelogPath(page);
            page.setRecords(attrGroupEntityList);
            return new PageUtils(page);
        } else {
            //否则根据分类id查
            String key = (String) params.get("key");
            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("catelog_id", catelogId);
            if (!StringUtils.isEmpty(key)) {
                wrapper.and((obj) -> {
                    obj.like("attr_group_name", key).or().like("descript", key);
                });
            }
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    wrapper
            );
            List<AttrGroupEntity> attrGroupEntityList = setCatelogPath(page);
            page.setRecords(attrGroupEntityList);
            return new PageUtils(page);
        }
    }

    /**
     * 获取属性分组的关联的所有属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> selectAttrs(Long attrgroupId) {
        List<AttrEntity> attrEntityList = new ArrayList<>();
        //在关联表查出所有的属性
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        //如果这个分组下的有属性
        if (!CollectionUtils.isEmpty(relationEntities)) {
            //将属性ids提取出来
            List<Long> attrIdList = relationEntities.stream()
                    .map(item -> {
                        return item.getAttrId();
                    })
                    .collect(Collectors.toList());
            //批量查询所有的属性
            attrEntityList = attrDao.selectBatchIds(attrIdList);
        }
        return attrEntityList;
    }

    /**
     * 添加属性与分组关联关系
     *
     * @param params
     */
    @Override
    public void saveAttr(Map<String, Object> params) {
        Long attrGroupId = (Long) params.get("attrGroupId");
        Long attrId = (Long) params.get("attrId");
        //在关联表添加属性和分组关联
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attrGroupId);
        relationEntity.setAttrId(attrId);
        relationDao.insert(relationEntity);
    }

    /**
     * 批量删除属性与分组的关联关系
     *
     * @param attrGroupEntityVos
     */
    @Override
    public void removeAttrsByIds(List<AttrGroupEntityVo> attrGroupEntityVos) {
        relationDao.deleteAttrsByGroupIds(attrGroupEntityVos);
    }

    /**
     * 添加属性与分组关联关系
     *
     * @param attrGroupEntityVos
     */
    @Override
    public void saveAttrs(List<AttrGroupEntityVo> attrGroupEntityVos) {
        relationDao.saveAttrs(attrGroupEntityVos);
    }

    /**
     * 获取分类下所有分组&关联属性
     *
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupEntityDto> withattrList(Long catelogId) {
        //返回数组
        List<AttrGroupEntityDto> attrGroupEntityDtos = new ArrayList<>();
        //先查出分类id下的所有分组
        List<AttrGroupEntity> attrGroupEntityList = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        if (!CollectionUtils.isEmpty(attrGroupEntityList)) {
            //分组信息拷贝到dto里面
            for (AttrGroupEntity attrGroupEntity : attrGroupEntityList) {
                AttrGroupEntityDto attrGroupEntityDto = new AttrGroupEntityDto();
                BeanUtils.copyProperties(attrGroupEntity, attrGroupEntityDto);
                attrGroupEntityDtos.add(attrGroupEntityDto);
            }
            attrGroupEntityDtos.stream()
                    .map(attrGroupEntityDto -> {
                        //查每个分组下的属性id
                        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupEntityDto.getAttrGroupId()));
                        //遍历查
                        List<Long> attrIds = relationEntities.stream().map(relationEntitie -> relationEntitie.getAttrId()).collect(Collectors.toList());
                        attrGroupEntityDto.setAttrs(attrDao.selectBatchIds(attrIds));
                        return attrGroupEntityDto;
                    });
        }
        return attrGroupEntityDtos;
    }


    /**
     * 设置分类完整路径
     */
    private List<AttrGroupEntity> setCatelogPath(IPage<AttrGroupEntity> page) {
        List<AttrGroupEntity> attrGroupEntityList = page.getRecords();
        attrGroupEntityList.forEach(attrGroupEntity -> {
            //递归找父分类
            List<Long> cateLogPathValues = categoryService.findCategoryPath(attrGroupEntity.getCatelogId(), new ArrayList<>());
            attrGroupEntity.setCatelogPath(cateLogPathValues);
        });
        return attrGroupEntityList;
    }

}